<?php
namespace app\manage\controller;
use think\Controller;

class KsyunUpload extends Controller
{
    private $client;

    //初始化连接金山云
    public function _initialize(){

        import("ksyun.Ks3Client");

        // $client = new \Ks3Client("qG1AhbRYCa3KyP7Gwede","pEtJzcdtkOWNdIElgLwtSoMIyUejbKAYuRKu8yC/","ks3-cn-beijing.ksyun.com");
        $client = new \Ks3Client("qG1AhbRYCa3KyP7Gwede","pEtJzcdtkOWNdIElgLwtSoMIyUejbKAYuRKu8yC/","ks3-cn-beijing-internal.ksyun.com");
        $this->client = $client;
    }

    /**
     * 普通方式上传
     * @param  [type] $bucketName 桶名称
     * @param  [type] $filePath   上传的文件路径
     * @param  [type] $fileName   存储于金山云的文件名称
     * @return [type] array       返回布尔值
     */
    public function put($bucketName, $filePath, $fileName){
        if( !isset($bucketName) || !isset($filePath) || !isset($fileName) ){
            return false;
        }

        $content = fopen($filePath, "r");
        $args = array(
            "Bucket"=>$bucketName,
            "Key"=>$fileName,
            "Content"=>array(//要上传的内容
                "content"=>$content,//可以是文件路径或者resource
                "seek_position"=>0//跳过文件开头?个字节
            ),
            "ACL"=>"public-read",//可以设置访问权限,合法值,private、public-read
            "ObjectMeta"=>array(//设置object的元数据,可以设置"Cache-Control","Content-Disposition","Content-Encoding","Content-Length","Content-MD5","Content-Type","Expires"。当设置了Content-Length时，最后上传的为从seek_position开始向后Content-Length个字节的内容。当设置了Content-MD5时，系统会在服务端进行md5校验。
                "Content-Type"=>"binay/ocet-stream",
            ),
            "UserMeta"=>array(//可以设置object的用户元数据，需要以x-kss-meta-开头
                "x-kss-meta-test"=>"test"
            )
        );

        $rs = $this->client->putObjectByFile($args);

        //返回下载地址
        if($rs['ETag']){
            $urlArr = explode('-', $bucketName);
            $url = $urlArr[2];
            return 'http://cdn.' . $url . '.miyuhaiwai.com/' . $fileName;
        }else{
            return false;
        }
    }

    //查看桶数据
    public function show($bucketName=''){
        $bucketName = input('bucket_name');
        //miyu-game-img-bucket
            //channel_material/文件名    渠道素材
            //  官网素材

        $args = array(
            "Bucket"=>$bucketName
        );
        $rs = $this->client->listObjects($args);
        p($rs);
    }

    /**
     * 文件删除
     * @param  [type] $bucketName 桶名
     * @param  [type] $key        存储于金山云的文件名称
     * @return [type]             返回布尔值
     */
    public function delete($bucketName='', $key=''){
        if(!isset($bucketName) || !isset($key)){
            return false;
        }

        $args = array(
            "Bucket"=>$bucketName,
            "Key"=>$key
        );
        $rs = $this->client->deleteObjects($args);
        return $rs;
    }

}